﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace TO3ChatServer
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        //服务器的Socket
        private Socket serverSocket = null;

        //服务启动标志：控制启动与停止
        private bool isListen = true;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void BtnStart_Click(object sender, RoutedEventArgs e)
        {
            //监听（Accept）也需要断开线程
            if (serverSocket==null)
            {
                isListen = true;
                //服务器地址：测试使用本地地址127.0.0.1
                IPAddress ip = IPAddress.Parse("127.0.0.1");
                IPEndPoint iep = new IPEndPoint(ip, 18888);
                //创建Socket
                serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //绑定
                serverSocket.Bind(iep);
                //监听
                serverSocket.Listen(100);
                //启动线程开启服务响应
                Thread t = new Thread(StartListen);
                //后台运行模式
                t.IsBackground = true;
                t.Start();
                //提示信息，异步模式更新UI显示
                TxtMsg.Dispatcher.BeginInvoke(new Action(()=>{ TxtMsg.Text += "服务器启动...\r\n"; }));
            }
        }

        private void BtnStop_Click(object sender, RoutedEventArgs e)
        {
            
        }

        /// <summary>
        /// 该函数是服务端Socket
        /// </summary>
        private void StartListen()
            {
                 //创建客户端的套接字
                 Socket clientSocket = default(Socket);
            try
            {
                //阻塞
                clientSocket = serverSocket.Accept();
                //
                byte[] bytesFrom = new byte[4096];
                string dataFromClent = null;
                int len = clientSocket.Receive(bytesFrom);
                if (len>0)
                {
                    dataFromClent = Encoding.UTF8.GetString(bytesFrom,0, len);
                }
            }
            catch (Exception e)
            {
                if (clientSocket != null&&!clientSocket.Connected)
                {
                    clientSocket.Close();
                    clientSocket = null;
                }
                Debug.WriteLine(e.ToString());
            }
            }
    }
}
